const router = require('koa-router')()
const mongoose = require('mongoose')
const upload = require('../upload')
const statsfn = require('../lib/statsfn')
const crypto = require('crypto')

router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.post('/', upload.single('imgfile'), async (ctx, next) => {
  const {title, description, imgUser} = ctx.req.body
  const {originalname, mimetype, filename: diskfilename} = ctx.req.file
  const doc = await Image.create({
    title, description, originalname, mimetype, diskfilename, imgUser
  })
  ctx.redirect(`/images/show/${doc._id}`)
})

router.get('/show/:id', async ctx => {
  ctx.session.user = 'abc'
  const doc = await Image.findByIdAndUpdate(
    ctx.params.id,
    {$inc: {visit: 1}},
    {new: true}
  )
  doc.stats = await statsfn()
  doc.comments = await Comment.find({image: ctx.params.id})
    .sort({createdAt: -1})
  
  doc.Allcomments = await Comment.find({})
    .sort({createdAt: -1})
    .limit(3)
  
  doc.user = ctx.session.user
  await ctx.render('show', doc)
})

router.post('/likes/:id',async ctx => {
  ctx.body = await Image.findByIdAndUpdate(
    ctx.params.id,
    {$inc:{likes: 1}},
    {new: true}
  )
})

router.get('/login', async ctx => {
  await ctx.render('login')
})
router.post('/login', async ctx => {
  let {username, password} = ctx.request.body
  // if(username === 'tom' && password === '123') {
  //   ctx.session.user = {nickname: '汤姆', username: 'tom'}
  let user = await User.find({username: username})
  const hash = crypto.createHash('md5')
  hash.update(password)
  password = hash.digest('hex')

  if(password === user[0].password){   
    ctx.session.user = user[0]
    ctx.redirect('/')
  }
})

router.get('/register', async ctx => {
  await ctx.render('register')
})

router.post('/register', async ctx => {
  let {username, password, nickname, email} = ctx.request.body
  const hash = crypto.createHash('md5')
  hash.update(password)
  password = hash.digest('hex')

  const user = await User.create({
    username, password, nickname, email
  })
  ctx.redirect('/')
})

router.get('/logout', async ctx => {
  ctx.session.user = undefined
  ctx.redirect('/')
})

module.exports = router